/*
 Copyright (c) Whitemice Consulting, 2007, 2008, 2009
 Adam Tauno Williams <awilliam@whitemice.org>
 License: MIT/X11

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.
 
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
*/
using System;
using System.Net;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.DirectoryServices;
using Whitemice.ZOGI;
using Nini.Config;

namespace Whitemice.ZOGI.Utilities 
{
  public class LDAPTeamSync :ZOGITool
  {
    int                           counter = 0;
    IConfigSource                 ini;

    public static void Main(string[] args)
    {
      new LDAPTeamSync(args);
    }
	
    public LDAPTeamSync(string[] args) : base(args)
    {
    }

    protected string DSAHost { get; set; }
    protected string BindDN { get; set; }
    protected string BindSecret { get; set; }
    protected string DSARoot { get; set; }
    protected string DSAFilter { get; set; }
    protected string GroupAttribute { get; set; }
    protected string UIDAttribute { get; set; }
    protected bool   X500Mode { get; set; }
    
    public override void LoadConfiguration()
    {
      // Access config directives
      try
      {
        ini = new IniConfigSource("OGoMojo.ini");
        /* Global settings */
        DSAHost = ini.Configs["OGoMojo"].Get("DSA");
        BindDN = ini.Configs["OGoMojo"].Get("BindDN");
        BindSecret = ini.Configs["OGoMojo"].Get("BindSecret");
        DSARoot = ini.Configs["LDAPTeamSync"].Get("Base");
        DSAFilter = ini.Configs["LDAPTeamSync"].Get("Filter");
        GroupAttribute = ini.Configs["LDAPTeamSync"].Get("GroupAttribute");
        if (ini.Configs["LDAPTeamSync"].Get("Mode") == "X500")
        {
          X500Mode = true;
        } else
          {
            X500Mode = false;
   				  UIDAttribute = ini.Configs["LDAPTeamSync"].Get("UserAttribute");
          }
      } catch (Exception _ex)
        {
          Console.WriteLine("Exception in retrieving configuration information");
          throw _ex;
        }
    }

    protected DirectoryEntry DSA { get; set; }
    
    protected void Bind()
    {
      DSA = new DirectoryEntry();
      DSA.AuthenticationType = AuthenticationTypes.None;
      DSA.Username = BindDN;
      DSA.Password = BindSecret;
      DSA.Path = string.Format("LDAP://{0}/{1}", DSAHost, DSARoot);
    }
    
    public override void Execute()
    {
      DirectorySearcher				search;
      int                    teamId;
      List<System.DirectoryServices.DirectoryEntry> dsaGroups;

      Bind();
      dsaGroups = new List<System.DirectoryServices.DirectoryEntry>();
      search = new DirectorySearcher(DSA);
      search.Filter = DSAFilter;
      Console.Write("Discovered DSA groups: ");
      foreach(SearchResult result in search.FindAll())
      {
        var group = result.GetDirectoryEntry();
        dsaGroups.Add(group);
        Console.Write("{0} ", group.Name);
      }
      Console.WriteLine();
      foreach (DirectoryEntry group in dsaGroups)
      {
        object result;
  
        teamId = Convert.ToInt32(group.Properties["opengroupwareid"][0]);
        result = Server.Connection.Get(teamId, 128, true);
        if (result == null)
        {
          Console.WriteLine("ObjectId#{0} not found on server.", teamId);
        } else if (result is Whitemice.ZOGI.Team)
          {
            ProcessGroup((result as Whitemice.ZOGI.Team), group);
          } else
            {
              Console.WriteLine("ObjectId#{0} is not a team.", teamId);
            }
      }
    } // end Execute
    
    protected void ProcessGroup(Team team, DirectoryEntry group)
    {
      IList<int> members;
      object[]  dsaIds;

      try
      {
        members = new List<int>();
        Console.WriteLine("LDAP Group: {0} ", group.Path);
        Console.WriteLine("OpenGroupware Team: ObjectId#{0} \"{1}\"", team.ObjectId, team.Name);
        Console.WriteLine("Team has {0} members prior to modification.", team.MemberCount);
        Console.Write("Member: ");
        dsaIds = (object[])group.Properties[GroupAttribute].Value;
        foreach(object ldapUID in dsaIds)
        {
          string  uid;
          Contact member;

          if (X500Mode)
          {
            DirectoryEntry user;
            user = new DirectoryEntry();
            user.AuthenticationType = AuthenticationTypes.None;
            user.Username = BindDN;
            user.Password = BindSecret;
            user.Path = string.Format("LDAP://{0}/{1}", DSAHost, ldapUID);
            user.Close();
            uid = group.Properties["uid"].Value.ToString();
          } else uid = ldapUID.ToString();
          member = Server.Connection.GetForLogin(uid);
          if (member == null)
          {
            Console.Write("{0}/NA ", uid);
            continue;
          }
        	Console.Write("{0}/OGo#{1} ", uid, member.ObjectId);
          members.Add(member.ObjectId);
        } // foreach team member
        Console.WriteLine();
        Console.WriteLine("{0} of {1} LDAP members have corresponding OGo accounts.",
          members.Count,
          dsaIds.Length);
        team.SetMembers(members);
        Server.Connection.Put(team);
      } catch (Exception ex)
        {
          Console.WriteLine("Exception updating team.");
          Console.WriteLine(ex.Message);
          Console.WriteLine(ex.StackTrace);
        }
        finally
        {
          Console.WriteLine();
          counter--;
        }
	  } // end Callback
  }
}
